package com.xstablet.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.lib.app.ARouterPathUtils;
import com.lib.app.CodeUtil;
import com.lib.fastkit.db.shared_prefrences.SharedPreferenceManager;
import com.lib.fastkit.db.shared_prefrences.interfaces.UserCacheInterface;
import com.lib.fastkit.http.ok.HttpUtils;
import com.lib.fastkit.utils.json_deal.lib_mgson.MGson;
import com.lib.fastkit.utils.log.LogUtil;
import com.lib.fastkit.utils.share.tool.StringUtil;
import com.lib.fastkit.views.dialog.normal.CoachAIStudyDialog;
import com.lib.fastkit.views.dialog.normal.OneButtonDialog;
import com.lib.fastkit.views.load_state_view.MultiStateView;
import com.lib.fastkit.views.recyclerview.tool.MyLinearLayoutManager;
import com.lib.fastkit.views.recyclerview.zhanghongyang.base.ViewHolder;
import com.lib.fastkit.views.spring_refresh.container.DefaultFooter;
import com.lib.fastkit.views.spring_refresh.container.DefaultHeader;
import com.lib.fastkit.views.spring_refresh.widget.SpringView;
import com.lib.http.call_back.HttpDialogCallBack;
import com.lib.http.call_back.HttpNormalCallBack;
import com.lib.observer.ObserverListener;
import com.lib.ui.adapter.BaseAdapter;
import com.lib.ui.fragment.BaseAppFragment;
import com.lib.utls.glide.GlideConfig;
import com.xstablet.R;
import com.xstablet.bean.CareStateBean;
import com.xstablet.bean.MainInfoBean_1;
import com.xstablet.bean.ToLiveBean;
import com.xstablet.bean.coachstudy.MainStudyListBean;
import com.xstablet.bean.newdayi.ConnectToLiveRoom;
import com.xstablet.bean.newdayi.StudentQuestionListBean;
import com.xstablet.view.popuputil.AutoPollRecyclerView;

import java.util.ArrayList;
import java.util.List;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

public class MainTeacherFragment extends BaseAppFragment implements ObserverListener {

    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.rv_questionlist)
    RecyclerView rvQuestionlist;
    @BindView(R.id.rv_studylist)
    RecyclerView rvStudylist;
    //    @BindView(R.id.springView)
//    SpringView springView;
    @BindView(R.id.state_view)
    MultiStateView stateView;

    @BindView(R.id.tv_morerecord)
    TextView tvMorerecord;
    @BindView(R.id.rv_record)
    AutoPollRecyclerView rvRecord;
    @BindView(R.id.lin_more_record)
    LinearLayout linMoreRecord;

    @BindView(R.id.tv_morevideo)
    TextView tvMorevideo;
    @BindView(R.id.rv_video)
    RecyclerView rvVideo;
    @BindView(R.id.sl_more_video)
    CardView slMoreVideo;

    //尖课、短视频适配器
    ShortVideoInfoAdapter videoAdapter;
    AutoPollAdapter autoPollAdapter;

    //首页老师、尖课、短视频数据容器
    List<MainInfoBean_1.ObjBean.RecordingClassBean> recordList = new ArrayList<>();
    List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> videoList = new ArrayList<>();

    //问题列表适配器
    QuestionListAdapter questionListAdapter;
    //首页学生问题数据容器
    List<StudentQuestionListBean.ObjBean> questionList = new ArrayList<>();


    //问题列表适配器
    CoachStudyListAdapter coachStudyListAdapter;
    //首页学生问题数据容器
    List<MainStudyListBean.ObjBean.RowsBean> studyList = new ArrayList<>();
    int page = 0;

    @Override
    protected void onCreateView(View view, Bundle savedInstanceState) {

        stateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
        stateView.setMultiStateViewLisener(new MultiStateView.MultiStateViewLisener() {
            @Override
            public void onTryAgain() {

//                initTopView();
                //获取在线答疑数据
                initQuestionListData();

                //获取辅导作业数据
                initCoachStudyListData();
            }
        });

        initView();

        //获取录播课和短视频数据
        initMainInfoData();

        //获取在线答疑数据
        initQuestionListData();

        //获取辅导作业数据
        initCoachStudyListData();

    }

    private void initView() {

//        springView.setHeader(new DefaultHeader(getActivity()));
//        springView.setFooter(new DefaultFooter(getActivity()));
//        springView.setEnableFooter(false);
//        springView.setListener(new SpringView.OnFreshListener() {
//            @Override
//            public void onRefresh() {
//                page = 0;
//                initCoachStudyListData();
//                initQuestionListData();
//                springView.onFinishFreshAndLoad();
//            }
//
//            @Override
//            public void onLoadmore() {
//                ++page;
//                initCoachStudyListData();
//                initQuestionListData();
//                springView.onFinishFreshAndLoad();
//            }
//        });

        questionListAdapter = new QuestionListAdapter(getActivity(), questionList);
        MyLinearLayoutManager managerQues = new MyLinearLayoutManager(getActivity());
        rvQuestionlist.setAdapter(questionListAdapter);
        rvQuestionlist.setLayoutManager(managerQues);

        coachStudyListAdapter = new CoachStudyListAdapter(getActivity(), studyList);
        MyLinearLayoutManager managerStudy = new MyLinearLayoutManager(getActivity());
        rvStudylist.setAdapter(coachStudyListAdapter);
        rvStudylist.setLayoutManager(managerStudy);

//        recordAdapter = new RecordClassInfoAdapter(getActivity(), recordList);
        autoPollAdapter = new AutoPollAdapter(getActivity(), recordList);
        MyLinearLayoutManager manager1 = new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.HORIZONTAL, false);
//        rvRecord.setAdapter(recordAdapter);
        rvRecord.setLayoutManager(manager1);
        rvRecord.setAdapter(autoPollAdapter);
        if (true) {//保证itemCount的总个数宽度超过屏幕宽度->自己处理
            rvRecord.start();
        }

        videoAdapter = new ShortVideoInfoAdapter(getActivity(), videoList);
        MyLinearLayoutManager manager2 = new MyLinearLayoutManager(getActivity(), MyLinearLayoutManager.HORIZONTAL, false);
        rvVideo.setAdapter(videoAdapter);
        rvVideo.setLayoutManager(manager2);

        rvVideo.setOnScrollListener(new RecyclerView.OnScrollListener() {
                //用来标记是否正在向最后一个滑动
                boolean isSlidingToLast = false;

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    // 当不滚动时
                    if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                        //获取最后一个完全显示的ItemPosition
                        int lastVisibleItem = manager.findLastCompletelyVisibleItemPosition();
                        int totalItemCount = manager.getItemCount();

                        // 判断是否滚动到底部，并且是向右滚动
                        if (lastVisibleItem == (totalItemCount - 1) && isSlidingToLast) {
                            //加载更多功能的代码
//                        slMoreVideo.setVisibility(View.VISIBLE);
                        }
                    }
                }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //dx用来判断横向滑动方向，dy用来判断纵向滑动方向
                if (dx > 0) {
                    //大于0表示正在向右滚动
                    isSlidingToLast = true;
                } else {
                    //小于等于0表示停止或向左滚动
                    isSlidingToLast = false;
                    slMoreVideo.setVisibility(View.GONE);
                }
            }
        });

    }

    private void initCoachStudyListData() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "STUDENT_QUESTION_LIST")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("page", page)
                .addParam("limit", 15)
                .execute(new HttpNormalCallBack<MainStudyListBean>() {
                    @Override
                    public void onSuccess(MainStudyListBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {
                                if (page == 0) {
                                    if (studyList.size() > 0) {
                                        studyList.clear();
                                    }
                                }
                                studyList.addAll(result.getObj().getRows());
                                coachStudyListAdapter.notifyDataSetChanged();

                            }
                            stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            stateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        }
                    }

                    @Override
                    public void onError(String e) {
                        if (stateView != null) {
                            stateView.setViewState(MultiStateView.VIEW_STATE_NETWORK_ERROR);
                        }
                    }
                });

    }


    private void initQuestionListData() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "QUESTIONS_FROM_STUDENTS")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<StudentQuestionListBean>() {
                    @Override
                    public void onSuccess(StudentQuestionListBean result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {
                                if (questionList.size() > 0) {
                                    questionList.clear();
                                }
                                questionList.addAll(result.getObj());
                                questionListAdapter.notifyDataSetChanged();

                            }
                            stateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                        } else {
                            stateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                        }
                    }

                    @Override
                    public void onError(String e) {
                        if (stateView != null) {
                            stateView.setViewState(MultiStateView.VIEW_STATE_NETWORK_ERROR);
                        }
                    }
                });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_teacher_1;
    }

    @OnClick({R.id.tv_morevideo, R.id.tv_morerecord, R.id.iv_refresh})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.iv_refresh) {

            CoachAIStudyDialog.getInstance()
                    .setTitle("温馨提示")
                    .setContent("确定需要刷新连麦和AI作业辅导的列表数据吗？")
                    .setSureListener(new CoachAIStudyDialog.SurelListener() {
                        @Override
                        public void onSure() {

                            initCoachStudyListData();
                            initQuestionListData();
                        }
                    }).show(getFragmentManager());

        } else if (i == R.id.tv_morevideo) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_ShortVideoListActivity)
                    .navigation();

        } else if (i == R.id.tv_morerecord) {

            ARouter.getInstance().build(ARouterPathUtils.Tablet_JianKe_JianKeListActivity)
                    .navigation();

        }
    }

    private void initMainInfoData() {

        HttpUtils.with(getActivity())
                .addParam("requestType", "TABLET_HOME_DATA")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<MainInfoBean_1>() {
                    @Override
                    public void onSuccess(MainInfoBean_1 result) {

                        if (CodeUtil.CODE_200 == result.getCode()) {
                            if (result.getObj() != null) {

                                if (result.getObj().getRecording_class() != null) {
//                                    initRecordInfo(result.getObj().getRecording_class());
                                    if (recordList.size() > 0) {
                                        recordList.clear();
                                    }
                                    recordList.addAll(result.getObj().getRecording_class());
//                                    recordAdapter.notifyDataSetChanged();
                                    autoPollAdapter.notifyDataSetChanged();
                                }
                                if (result.getObj().getTeacher_short_video() != null) {
//                                    initShortVideoInfo(result.getObj().getTeacher_short_video());
                                    if (videoList.size() > 0) {
                                        videoList.clear();
                                    }
                                    videoList.addAll(result.getObj().getTeacher_short_video());
                                    videoAdapter.notifyDataSetChanged();
                                }

                                if (result.getObj().getCourse_order() != null) {
                                    if (StringUtil.isNotEmpty(result.getObj().getCourse_order().getCourse_id(), true)) {

                                        if (StringUtil.isNotEmpty(result.getObj().getCourse_order().getCourse_type() + "", true) ||
                                                StringUtil.isNotEmpty(result.getObj().getCourse_order().getCourse_id(), true)) {

                                            OneButtonDialog.getInstance()
                                                    .setTitle("温馨提示")
                                                    .setContent("您还有课程没有下课，是否立即进入直播间？")
                                                    .setSureListener(new OneButtonDialog.SurelListener() {
                                                        @Override
                                                        public void onSure() {

                                                            MainInfoBean_1.ObjBean.CourseOrderBean courseOrderBean = result.getObj().getCourse_order();

//                                                            goToClass(courseOrderBean.getCourse_type() + "",
//                                                                    courseOrderBean.getCourse_id());

                                                            goToClass(courseOrderBean.getCourse_type() + "", courseOrderBean.getCourse_id(),
                                                                    courseOrderBean.getUuid() + "", courseOrderBean.getRoomToken(),
                                                                    courseOrderBean.getRoomName() + "", courseOrderBean.getTeacherPhone(),
                                                                    courseOrderBean.getUserPhone() + "", courseOrderBean.getWhitetoken());
                                                        }
                                                    }).show(getFragmentManager());

                                        }
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });
    }

    //老师重连进入直播间
    private void goToClass(final String course_type, final String course_id,
                           final String uuid, final String roomToken,
                           final String roomName, final String teacherPhone,
                           final String userPhone, final String whitetoken) {


        LogUtil.e("teacherPhone=" + teacherPhone +
                "roomName=" + roomName + "uuid=" + uuid
                + "roomToken的值为：" + roomToken);


        ARouter.getInstance().build(ARouterPathUtils.Tablet_CoachStudyLivingActivity)
                .withString("roomToken", roomToken)
                .withString("uuid", uuid)
                .withString("teacherPhone", teacherPhone)
                .withString("roomName", roomName)
                .withString("userPhone", userPhone)
                .withString("whitetoken", whitetoken)
                .withString("course_id", course_id)
                .navigation();

    }


    //connectId生成本次连线的Id
    private void goToClass(int type, final String course_type, final String course_id, final int teacherId
            , final String studentHeadUrl, final String studentName, final int studentId) {

        //保存课程的类型以及该课程的Id，用于RoomControlFragment分享
        final UserCacheInterface userCacheInterface = SharedPreferenceManager.getInstance(getActivity()).getUserCache();
        userCacheInterface.setBussessType(course_type);
        userCacheInterface.setCourseId(course_id);

        //type:0晚陪课，1一对一，2班级课，3体验课
        //支付了去上课
        HttpUtils.with(getActivity())
                .addParam("requestType", "TO_CLASS")
                .addParam("course_type", course_type)
                .addParam("course_id", course_id)
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpDialogCallBack<ToLiveBean>() {
                    @Override
                    public void onSuccess(ToLiveBean result) {

                        if (result.getCode() == CodeUtil.CODE_200) {

                            String roomToken = result.getObj().getRoomtoken();
                            String teacherPhone = result.getObj().getPhoen();

                            LogUtil.e("teacherPhone=" + teacherPhone +
                                    "roomName=" + result.getObj().getRoomname() + "uuid=" + result.getObj().getUuid()
                                    + "roomToken的值为：" + roomToken);

                            if (type == 0) {
                                ARouter.getInstance().build(ARouterPathUtils.Tablet_Live_LiveRoomActivity)
                                        .withString("roomToken", roomToken)
                                        .withString("teacherPhone", teacherPhone)
                                        .withString("roomName", result.getObj().getRoomname())
                                        .withString("userPhone", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone())
                                        .withString("uuid", result.getObj().getUuid())
                                        .withString("whitetoken", result.getObj().getWhitetoken())
                                        .withString("studentHeadUrl", studentHeadUrl)
                                        .withString("studentName", studentName)
                                        .withInt("studentId", studentId)
                                        .withInt("teacherId", teacherId)
                                        .withString("course_id", course_id)
                                        .navigation();

                            } else {
                                ARouter.getInstance().build(ARouterPathUtils.Tablet_CoachStudyLivingActivity)
                                        .withString("roomToken", roomToken)
                                        .withString("teacherPhone", teacherPhone)
                                        .withString("roomName", result.getObj().getRoomname())
                                        .withString("userPhone", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserPhone())
                                        .withString("uuid", result.getObj().getUuid())
                                        .withString("whitetoken", result.getObj().getWhitetoken())
                                        .withString("course_id", course_id)
                                        .navigation();
                            }

                        } else {
                            showToast(result.getMsg());
                        }

                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

    @Override
    public void observerUpData(String content) {

        if (StringUtil.isNotEmpty(content, true)) {
            if ("updateNewShareCare".equals(content)) {
                //获取在线答疑数据
                initQuestionListData();

                //获取辅导作业数据
                initCoachStudyListData();
            }
        }

    }


    class ShortVideoInfoAdapter extends BaseAdapter<MainInfoBean_1.ObjBean.TeacherShortVideoBean> {

        public ShortVideoInfoAdapter(Context context, List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_video;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<MainInfoBean_1.ObjBean.TeacherShortVideoBean> mData) {

            FrameLayout linVideo = holder.getView(R.id.fr_video);
//            int screenWidth = DisplayUtil.getScreenWidth(getActivity());
//            ViewGroup.LayoutParams params = linVideo.getLayoutParams();
//            params.width = screenWidth / 6;
//            linVideo.setLayoutParams(params);

            MainInfoBean_1.ObjBean.TeacherShortVideoBean teacherVideoBean = mData.get(position);
            ImageView ivUser = holder.getView(R.id.iv_user);
            if (StringUtil.isNotEmpty(mData.get(position).getPhoto_url(), true)) {
                Glide.with(getActivity())
                        .load(mData.get(position).getPhoto_url())
                        .apply(GlideConfig.getCircleOptions())
                        .into(ivUser);
            }

            ivUser.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    ARouter.getInstance().build(ARouterPathUtils.Tablet_User_InfoActivity)
                            .withInt("teacherId", teacherVideoBean.getUser_id()).navigation();
                }
            });

            if (StringUtil.isNotEmpty(teacherVideoBean.getUser_name(), true)) {
                holder.setText(R.id.tv_video_username, teacherVideoBean.getUser_name());
            }
            if (StringUtil.isNotEmpty(teacherVideoBean.getPublish_date(), true)) {
                holder.setText(R.id.tv_video_usertime, teacherVideoBean.getPublish_date());
            }
            if (StringUtil.isNotEmpty(teacherVideoBean.getDynamic_content(), true)) {
                holder.setText(R.id.tv_video_content, teacherVideoBean.getDynamic_content());
            }

            //关注状态
            TextView tvCare = holder.getView(R.id.tv_video_care);
            if (1 == teacherVideoBean.getAttention_status()) {
                tvCare.setText("已关注");
                tvCare.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                tvCare.setTextColor(getActivity().getResources().getColor(R.color.newshare_care));
            }

            tvCare.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    //传递关注/取关到服务器
                    sendCareStateToService(tvCare, teacherVideoBean.getUser_id());
                }
            });

            ImageView ivVideoBg = holder.getView(R.id.iv_video);
            if (StringUtil.isNotEmpty(teacherVideoBean.getDynamic_hash_icon(), true)) {
                Glide.with(getActivity())
                        .load(teacherVideoBean.getDynamic_hash_icon())
                        .apply(GlideConfig.getRoundOptions(10))
                        .into(ivVideoBg);
            }

            holder.setOnClickListener(R.id.lin_info, new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    ARouter.getInstance().build(ARouterPathUtils.Tablet_User_InfoActivity)
                            .withInt("teacherId", teacherVideoBean.getUser_id()).navigation();
                }
            });

            linVideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    int teacher_id = teacherVideoBean.getUser_id();
                    int dynamic_id = teacherVideoBean.getDynamic_id();
                    ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_ShortVideoDetailActivity)
                            .withInt("teacher_id", teacher_id)
                            .withInt("dynamic_id", dynamic_id).navigation();

//                    int recordId = mData.get(position).getId();
//                    ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
//                            .withInt("recordId", recordId).navigation();

                }
            });

        }
    }

    public void sendCareStateToService(TextView tvCare, int userId) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "DYNAMIC_ATTENTION")
                .addParam("be_user_id", userId + "")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .execute(new HttpNormalCallBack<CareStateBean>() {
                    @Override
                    public void onSuccess(CareStateBean result) {

                        if (result != null) {
                            if (CodeUtil.CODE_200 == result.getCode()) {
                                if (0 == result.getObj().getAttention_status()) {
                                    tvCare.setText("关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_care_r_20);
                                    tvCare.setTextColor(getActivity().getResources().getColor(R.color.white));

                                } else if (1 == result.getObj().getAttention_status()) {
                                    tvCare.setText("已关注");
                                    tvCare.setBackgroundResource(R.drawable.bg_ran_cared_r_15);
                                    tvCare.setTextColor(getActivity().getResources().getColor(R.color.newshare_care));
                                }
                                showToast(result.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(String e) {
                        LogUtil.e(e.toString());
                    }
                });
    }

    public class AutoPollAdapter extends RecyclerView.Adapter<BaseViewHolder> {
        private final Context mContext;
        private final List<MainInfoBean_1.ObjBean.RecordingClassBean> mData;

        public AutoPollAdapter(Context context, List<MainInfoBean_1.ObjBean.RecordingClassBean> list) {
            this.mContext = context;
            this.mData = list;
        }

        @Override
        public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_record, parent, false);
            BaseViewHolder holder = new BaseViewHolder(view);
            return holder;
        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position) {

            FrameLayout linRecord = holder.getView(R.id.fr_record);
//            int screenWidth = DisplayUtil.getScreenWidth(getActivity());
//            ViewGroup.LayoutParams params = linRecord.getLayoutParams();
//            params.width = screenWidth / 4;
//            linRecord.setLayoutParams(params);

            MainInfoBean_1.ObjBean.RecordingClassBean classBean = null;

            if (mData.size() > 0) {
                if (position < mData.size()) {
                    classBean = mData.get(position);
                } else if (position > mData.size() || position == mData.size()) {
                    classBean = mData.get(position % mData.size());
                }
                ImageView ivRecordBg = holder.getView(R.id.iv_record);
                if (StringUtil.isNotEmpty(classBean.getCover(), true)) {
                    Glide.with(getActivity())
                            .load(classBean.getCover())
                            .apply(GlideConfig.getRoundOptions(10))
                            .into(ivRecordBg);
                }

                if (StringUtil.isNotEmpty(classBean.getVideo_title(), true)) {
                    holder.setText(R.id.tv_record, classBean.getVideo_title());
                }

                MainInfoBean_1.ObjBean.RecordingClassBean finalClassBean = classBean;
                linRecord.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

//                        int recordId = finalClassBen.getId();
//                        ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
//                                .withInt("recordId", recordId).navigation();

                        String recordJson = MGson.newGson().toJson(finalClassBean);
//                        String url = finalClassBean.getVideo_url();
                        LogUtil.e("录播课视频的数据为：" + recordJson);

                        ARouter.getInstance().build(ARouterPathUtils.Tablet_Video_RecordDetailActivity)
                                .withInt("recordId", finalClassBean.getId())
                                .withString("recordJson", recordJson).navigation();

                    }
                });
            }

        }

        @Override
        public int getItemCount() {
            return Integer.MAX_VALUE;
        }
    }

    class CoachStudyListAdapter extends BaseAdapter<MainStudyListBean.ObjBean.RowsBean> {

        public CoachStudyListAdapter(Context context, List<MainStudyListBean.ObjBean.RowsBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_connect_questionlist;
        }

        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<MainStudyListBean.ObjBean.RowsBean> mData) {

            if (mData.size() > 0 && mData != null) {
                final MainStudyListBean.ObjBean.RowsBean rowsBean = mData.get(position);

                ImageView ivUser = holder.getView(R.id.iv_connect_user);
                if (StringUtil.isNotEmpty(rowsBean.getPhoto_url(), true)) {
                    Glide.with(getActivity())
                            .applyDefaultRequestOptions(GlideConfig.getCircleOptions())
                            .load(rowsBean.getPhoto_url())
                            .into(ivUser);
                }
                if (StringUtil.isNotEmpty(rowsBean.getUser_name(), true)) {
                    holder.setText(R.id.tv_connect_name, rowsBean.getUser_name());
                }

                if (StringUtil.isNotEmpty(rowsBean.getGrade_name(), true)) {
                    holder.setText(R.id.tv_connect_subject, rowsBean.getGrade_name());
                }

                TextView tvAnswer = holder.getView(R.id.tv_connect_answer);
                tvAnswer.setText("辅导");

                tvAnswer.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //如果courseOrderBean不为空，代表辅导作业，需要先创建直播间
                        //根据学生Id去创建直播间
                        getAIStudyToRoom(rowsBean.getId(), rowsBean.getPhoto_url(),
                                rowsBean.getUser_name(), rowsBean.getUser_id());
                    }

                });

            }
        }
    }


    class QuestionListAdapter extends BaseAdapter<StudentQuestionListBean.ObjBean> {

        public QuestionListAdapter(Context context, List<StudentQuestionListBean.ObjBean> mData) {
            super(context, mData);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_connect_questionlist;
        }

        @SuppressLint("ResourceAsColor")
        @Override
        protected void toBindViewHolder(ViewHolder holder, int position, List<StudentQuestionListBean.ObjBean> mData) {

            if (mData.size() > 0 && mData != null) {
                final StudentQuestionListBean.ObjBean dataBean = mData.get(position);

                ImageView ivUser = holder.getView(R.id.iv_connect_user);
                if (StringUtil.isNotEmpty(dataBean.getPhoto_url(), true)) {
                    Glide.with(getActivity())
                            .applyDefaultRequestOptions(GlideConfig.getCircleOptions())
                            .load(dataBean.getPhoto_url())
                            .into(ivUser);
                }
                if (StringUtil.isNotEmpty(dataBean.getUser_name(), true)) {
                    holder.setText(R.id.tv_connect_name, dataBean.getUser_name());
                }

                if (StringUtil.isNotEmpty(dataBean.getSubject_name(), true)) {
                    holder.setText(R.id.tv_connect_subject, dataBean.getSubject_name());
                }

                TextView tvAnswer = holder.getView(R.id.tv_connect_answer);
                tvAnswer.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //根据学生Id去创建直播间
                        getConnectToRoom(dataBean.getPhoto_url(), dataBean.getUser_name(), dataBean.getId());
                    }
                });

            }
        }
    }

    private void getConnectToRoom(final String studentHeadUrl, final String studentName, final int studentId) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "CREATE_ORDER_CREATE_LIVE_BROADCAST")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("student_id", studentId)
                .execute(new HttpNormalCallBack<ConnectToLiveRoom>() {
                    @Override
                    public void onSuccess(ConnectToLiveRoom result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result.getObj().getCourse_id() > -1 && result.getObj().getCourse_type() > -1) {

                                goToClass(0, result.getObj().getCourse_type() + "",
                                        result.getObj().getCourse_id() + "",
                                        result.getObj().getTeacher_id(),
                                        studentHeadUrl, studentName, studentId);

                            }
                        } else if (474 == result.getCode()) {//该问题已有老师解答
                            showToast(result.getMsg());
                            initQuestionListData();
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }


    private void getAIStudyToRoom(int studyId, final String studentHeadUrl,
                                  final String studentName, final int studentId) {

        HttpUtils.with(getActivity())
                .addParam("requestType", "TEACHER_CREATES_LIVE_BROADCAST")
                .addParam("token", SharedPreferenceManager.getInstance(getActivity()).getUserCache().getUserToken())
                .addParam("id", studyId)
                .addParam("student_id", studentId)
                .execute(new HttpNormalCallBack<ConnectToLiveRoom>() {
                    @Override
                    public void onSuccess(ConnectToLiveRoom result) {
                        if (CodeUtil.CODE_200 == result.getCode()) {

                            if (result.getObj().getCourse_id() > -1 && result.getObj().getCourse_type() > -1) {
                                goToClass(studyId, result.getObj().getCourse_type() + "",
                                        result.getObj().getCourse_id() + "",
                                        result.getObj().getTeacher_id(),
                                        studentHeadUrl, studentName, studentId);
                            }
                        } else if (476 == result.getCode()) {

                            showToast(result.getMsg());
                            initCoachStudyListData();
                        }
                    }

                    @Override
                    public void onError(String e) {

                    }
                });

    }

}
